package com.boyunv.interpreter.example01;
/*
 *@description
 *  表达式解释器
 *@author boyunv
 *@create 2023/9/10 8:12
 *@version 1.0
 */

import java.util.Deque;
import java.util.LinkedList;

public class ExpressionInterpreter {
    
    //双向队列,可以从队列两端增加或者删除元素
    private Deque<Long>  numbers=new LinkedList<Long>();
    
    
    //接受表达式进行解析
    public  long interpreter(String expression){
        //9 5 7 3 - + *
        String[] element = expression.split(" ");
        int length=element.length;
        //获取表达式中数字
        for(int i=0;i< (length+1)/2;++i){
            //像集合的尾部去添加元素
            numbers.addLast(Long.parseLong(element[i]));
            
        }
        
        //获取表达式中符号,去进行计算
        for (int i =  (length+1)/2; i <length ; i++) {
            String operator=element[i];
            //判断符号是否为加减乘除
            boolean isValid="+".equals(operator)||"-".equals(operator)||"*".equals(operator)||"/".equals(operator);
            if(!isValid){
                throw new RuntimeException("无效表达式"+expression);
            }
            
            //获取集合中的数字;一出集合中的第一个元素,并且返回倍移除的值
            Long number1 = numbers.pollFirst();//数字
            Long number2 = numbers.pollFirst();//数字
            
            long  result=0;
            if("+".equals(operator)){
                result=number1+number2;
            }else  if("-".equals(operator)){
                result=number1-number2;
            } else  if("*".equals(operator)){
                result=number1*number2;
            }else  if("/".equals(operator)){
                result=number1/number2;
            }
            //将运算结果添加到集合头部
            numbers.addFirst(result);
        }
        
        //运算的最终结果保存在集合中
        if(numbers.size()!=1){
            throw new RuntimeException("无效表达式"+expression);
        }
        //移除我们集合唯一结果病返回
        return numbers.pop();
        
    }
}
